package edu.yuhf.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import edu.yuhf.dao.iface.EmpDao;
import edu.yuhf.domain.Emp;

@Repository(value="empDao")
public class EmpJdbcDaoImpl implements EmpDao {

	private Logger log=Logger.getLogger(EmpJdbcDaoImpl.class);
	@Resource
	JdbcTemplate jdbcTemplate;
	
	@Override
	public List<Emp> queryAll() {
		String sql="select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp";
		List<Emp> list=jdbcTemplate.query(sql,new RowMapper<Emp>() {
			public Emp mapRow(ResultSet rs, int rowNum) throws SQLException {
				Emp emp=new Emp();
				emp.setEmpno(rs.getInt(1));
				emp.setEname(rs.getString(2));
				emp.setJob(rs.getString(3));
				emp.setMgr(rs.getInt(4));
				emp.setHiredate(rs.getDate(5)==null?null:rs.getDate(5).toLocalDate());
				emp.setSal(rs.getBigDecimal(6));
				emp.setComm(rs.getBigDecimal(7));
				emp.setDeptno(rs.getInt(8));
				return emp;
			}
		});
		return list;
	}

	@Override
	public List<Emp> queryByName(String name) {
		String sql="select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp where ename=?";
		List<Emp> list=jdbcTemplate.query(sql,(rs,index)->
			new Emp(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getDate(5).toLocalDate(),rs.getBigDecimal(6),rs.getBigDecimal(7),rs.getInt(8)),
			new Object[] {name}
		);
		return list;
	}

	@Override
	public boolean insertEmp(Emp emp) {
		boolean flag=false;
		String sql="insert into Emp(empno,ename,job,mgr,hiredate,sal,deptno) ";
		sql+="values(?,?,?,?,?,?,?)";
		Object[] param=new Object[] {emp.getEmpno(),emp.getEname(),emp.getJob(),emp.getMgr(),java.sql.Date.valueOf(emp.getHiredate()),emp.getSal(),emp.getDeptno()};
		int rowNumber=jdbcTemplate.update(sql,param);
		if(rowNumber==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean delete(int id) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean update(Emp emp) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean checkNameAndPassword(String name, String password) {
		log.debug("checkNameAndPassword method...");
		boolean flag=false;
		String sql="select count(*) from emp where ename=? and empno=?";
		int rowNumber=jdbcTemplate.queryForObject(sql, Integer.class,new Object[] {name,password});
		if(rowNumber==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean updateEmp(int empno, Emp emp) {
		// TODO Auto-generated method stub
		return false;
	}

}
